package com.project.market.service.impl;

import com.project.market.db.domain.MarketRegion;
import com.project.market.db.domain.MarketRegionExample;
import com.project.market.db.mapper.MarketRegionMapper;
import com.project.market.service.AdminRegionService;
import com.project.market.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AdminRegionServiceImpl implements AdminRegionService {
    @Override
    public List<Object> list() {
        SqlSession session = MybatisUtil.getSession();
        MarketRegionMapper mapper = session.getMapper(MarketRegionMapper.class);

        MarketRegionExample example1 = new MarketRegionExample();
        example1.createCriteria().andTypeEqualTo((byte) 1);
        List<MarketRegion> marketRegions1 = mapper.selectByExample(example1);

        MarketRegionExample example2 = new MarketRegionExample();
        example2.createCriteria().andTypeEqualTo((byte) 2);
        List<MarketRegion> marketRegions2 = mapper.selectByExample(example2);

        MarketRegionExample example3 = new MarketRegionExample();
        example2.createCriteria().andTypeEqualTo((byte) 3);
        List<MarketRegion> marketRegions3 = mapper.selectByExample(example3);


        ArrayList<Object> list = new ArrayList<>();
        HashMap<Object, Object> map1;
        HashMap<Object, Object> map;


        for (MarketRegion marketRegion : marketRegions1) {
            map1 = new HashMap<>();
            map1.put("id", marketRegion.getId());
            map1.put("name", marketRegion.getName());
            map1.put("type", marketRegion.getType());
            map1.put("code", marketRegion.getCode());
            ArrayList<Object> objects1 = new ArrayList<>();

            for (MarketRegion region : marketRegions2) {
                map = new HashMap<>();
                map.put("id", region.getId());
                map.put("name", region.getName());
                map.put("type", region.getType());
                map.put("code", region.getCode());

                if (region.getPid().equals(marketRegion.getId())) {
                    objects1.add(map);

                    ArrayList<Object> objects = new ArrayList<>();
                    for (MarketRegion reg : marketRegions3) {
                        if (reg.getPid().equals(region.getId())) {
                            objects.add(reg);

                        }
                    }
                    map.put("children", objects);
                }
            }

            map1.put("children", objects1);

            list.add(map1);
        }

        session.commit();
        session.close();
        return list;
    }
}
